from coin.support.feed_tool.feed_stats.app.feed_latency_stats.metadata_importer import FeedStatsImporter
from sqlalchemy.ext.automap import automap_base
from absl import app, flags
from datetime import datetime

FLAGS = flags.FLAGS

class LatencyStatsCleaner(FeedStatsImporter):
  def __init__(self):
    super().__init__()
    base = automap_base()
    base.prepare(autoload_with=self._engine)
    self._FeedLatencyStats = base.classes.FeedLatencyStats

  def clean_outdated_latency_data(self,date):
    session=self._get_session()
    session.query(self._FeedLatencyStats).filter(
      self._FeedLatencyStats.start_time < date).delete(synchronize_session="fetch")
    # session.rollback()
    session.commit()

def main(_):
  date = datetime.strptime(FLAGS.hold_start_date, '%Y%m%d')
  cleaner = LatencyStatsCleaner()
  cleaner.clean_outdated_latency_data(date)
  
if __name__ == '__main__':
  flags.DEFINE_string('hold_start_date', None, 'earliest date of data, yyyymmdd')
  app.run(main)